package com.example.demo.web.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.function.Consumer;

public class JsonUtils {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    static {
        OBJECT_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    public static void checkJson(@NonNull String jsonContent) throws JsonProcessingException {
        toJson(jsonContent);
    }

    public static JsonNode toJson(@NonNull String jsonContent) throws JsonProcessingException {
        return OBJECT_MAPPER.readTree(jsonContent);
    }

    public static JsonNode readFromFile(@NonNull File file) throws IOException {
        return OBJECT_MAPPER.readTree(file);
    }

    public static String toJson(@NonNull Object obj) throws JsonProcessingException {
        return OBJECT_MAPPER.writeValueAsString(obj);
    }

    public static <T> T toObj(@NonNull JsonNode node, Class<T> clz) throws JsonProcessingException {
        return OBJECT_MAPPER.readValue(node.toString(), clz);
    }

    public static <T> T toObj(@NonNull String json, Class<T> clz) throws JsonProcessingException {
        return OBJECT_MAPPER.readValue(json, clz);
    }

    public static void forEntry(@NonNull JsonNode node, @NonNull Consumer<Map.Entry<String, JsonNode>> consumer) {
        Iterator<Map.Entry<String, JsonNode>> it = node.fields();
        while (it.hasNext()) {
            consumer.accept(it.next());
        }
    }

    public static boolean isEmptyNode(@Nullable JsonNode node) {
        return node == null || node.isNull();
    }

    public static ObjectNode createNode() {
        return OBJECT_MAPPER.createObjectNode();
    }

    /**
     * 去掉花括号
     */
    public static String xJson(JsonNode node) {
        String content = node.toString();
        return content.substring(1, content.length() - 1);
    }
}
